import express from 'express';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import open from 'open';
import { aliyunCode, baiduCode } from './utils/langueCode.js';
import execVue from './index.js';
import pathTranslattionJs from './pathTranslattionJs.js';
import pathTranslattionJson from './pathTranslattionJson.js';

// 获取当前模块的目录名
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
const PORT = 3002;

// 存储所有活动的SSE连接
const clients = new Set();

// 重写process.stdout.write以捕获控制台输出
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
const originalStderrWrite = process.stderr.write.bind(process.stderr);
process.stdout.write = (chunk) => {
  originalStdoutWrite(chunk); // 保持原始控制台输出
  broadcastMessage({
    type: 'info',
    content: chunk.toString(),
    timestamp: new Date().toISOString()
  });
};
process.stderr.write = (chunk) => {
  originalStderrWrite(chunk); // 保持原始控制台输出
  broadcastMessage({
    type: 'error',
    content: chunk.toString(),
    timestamp: new Date().toISOString()
  });
};



// 配置静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 中间件解析JSON请求体
app.use(express.json());



// SSE路由
app.get('/sse', (req, res) => {
  // 设置SSE相关头部
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  res.flushHeaders();

  // 添加客户端到集合中
  clients.add(res);

  // 发送初始连接消息
  res.write('data: Connected to SSE server\n\n');

  // 监听客户端断开连接
  req.on('close', () => {
    clients.delete(res);
  });
});

// 广播消息给所有连接的客户端
function broadcastMessage(message) {
  const data = `data: ${JSON.stringify(message)}\n\n`;
  clients.forEach(client => {
    try {
      client.write(data);
    } catch (err) {
      // 如果客户端已关闭，从集合中移除
      clients.delete(client);
      console.error('客户端连接已关闭，已移除');
    }
  });
}

// 示例接口1：返回服务器信息
app.get('/getLangCode', (req, res) => {
  res.json({
    data: {
      aliyun: aliyunCode,
      baidu: baiduCode
    },
    timestamp: new Date().toISOString()
  });
});

// 示例接口2：处理POST请求
app.post('/start', async (req, res) => {
  const config = req.body;
  try {
    if(config.scanPath!='./source'){
      //读取package.json  修改i18nPickConfig.srcCodeDir节点为config.scanPath的值后重新写入文件
      const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf-8'))
      packageJson.i18nPickConfig.srcCodeDir = config.scanPath
      fs.writeFileSync('./package.json',JSON.stringify(packageJson, null, 2))
    }
    if (config.activeTab == 'translation-patch') {
      if (config.patchTranslation.fileType == 'js') {
        await pathTranslattionJs(config)
      } else if (config.patchTranslation.fileType == 'json') {
        await pathTranslattionJson(config)
      }
    } else {
      await execVue(config)
    }
  } catch (error) {
    console.error('处理POST请求时出错：', error);
  } finally {
    res.json({
      received: true,
      message: 'start',
      timestamp: new Date().toISOString()
    });
  }
});

// 新增接口：发送消息到所有SSE客户端
app.post('/api/broadcast', (req, res) => {
  const { message } = req.body;
  broadcastMessage({
    type: 'broadcast',
    content: message,
    timestamp: new Date().toISOString()
  });
  res.json({ success: true, message: 'Message broadcasted' });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
  open(`http://localhost:${PORT}`)
});